<?php

namespace App\Services;

use App\Exceptions\AdminInvalidRequestException;
use App\Models\Reception;
use Dcat\Admin\Models\Administrator;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use App\Enums\UserStatus;
use App\Models\Department;
use App\Models\Ding;
use App\Models\User;
use EasyDingTalk\Application;
use Illuminate\Support\Arr;

class DingTalkPush
{

    public Application $app;

    public $ding;

    public function __construct(string $corp_id)
    {
        $this->ding = Ding::query()->where('corp_id', $corp_id)->first();
        $this->app = new Application(array_merge(config('ding'), $this->ding->toArray()));
    }

    /**
     * 通讯录用户增加
     * @param array $payload
     * @param bool $modify
     */
    public function userAddOrg(array $payload,)
    {
        foreach ($payload['UserId'] as $item_user_id) {

            //获取新用户的数据，然后存储到员工表中
            $user = $this->app->user->get($item_user_id);
            if ($user['errcode']) {
                //请求错误
                continue;
            }
            $user = $user['result'];
            //下面是之前的流程，暂时不使用
            User::updateOrCreate(
                ['userid' => $user['userid'], 'status' => UserStatus::WORKING, 'ding_id' => $this->ding->id],
                [
                    'dept_id' => Arr::first($user['dept_id_list']),
                    'name' => $user['name'],
                    'phone' => $user['mobile'],
                    'avatar' => $user['avatar'] ?: asset('images/default.jpg'),
                    'userid' => $user['userid'],
                    'unionid' => $user['unionid']
                ]
            );
            //花名重复检测
            $users = User::query()->where('status', UserStatus::WORKING)->where('name', $user['name'])->get();
            if ($users->count() >= 2) {
                $str = '';
                foreach ($users as $item) {
                    $str .= '花名：' . $item->name . '，公司：' . $item->ding->name . '，部门：' . $item->department->name . PHP_EOL;
                }
                ding()->at(['18682622927', '15281045086'])
                    ->text('员工花名重复，信息如下：' . PHP_EOL . $str);
            }
        }
    }

    //通讯录用户信息变更
    public function userModifyOrg(array $payload)
    {
        $this->userAddOrg($payload);
    }

    //通讯录用户离职
    public function userLeaveOrg(array $payload)
    {
        foreach ($payload['UserId'] as $item_user_id) {
            if ($user = User::query()->where('userid', $item_user_id)->where('ding_id', $this->ding->id)->where('status', UserStatus::WORKING)->first()) {
                $user->status = UserStatus::DEPART;
                if ($user->admin_user_id) {
                    //如果开通了后台权限，则删除
                    $admin = Administrator::query()->find($user->admin_user_id);
                    $admin->roles()->detach();
                    $admin->delete();
                    $user->admin_user_id = 0;
                }
                //如果离职了并且是接待人员，自动关闭接待状态
                if ($reception = Reception::query()->where('user_id', $user->id)->where('status', true)->first()) {
                    $reception->status = false;
                    $reception->save();
                }
                $user->save();
            }
        }
    }


    //部门创建
    public function orgDeptCreate(array $payload)
    {
        foreach ($payload['DeptId'] as $item) {
            if (!Department::query()->where('ding_id', $this->ding->id)->where('dept_id', $item)->exists()) {
                //获取部门信息,然后判断存储
                $department = $this->app->department->get($item);
                if ($department['errcode']) {
                    //请求错误
                    continue;
                }
                Department::query()->create([
                    'ding_id' => $this->ding->id,
                    'dept_parent_id' => $department['result']['parent_id'],
                    'dept_id' => $department['result']['dept_id'],
                    'name' => $department['result']['name']
                ]);
            }
        }
    }


    //部门删除
    public function orgDeptRemove(array $payload)
    {
        foreach ($payload['DeptId'] as $item) {
            if ($department = Department::query()->where('dept_id', $item)->where('ding_id', $this->ding->id)->first()) {
                $department->delete();
            }
        }
    }


    //部门修改
    public function orgDeptModify(array $payload)
    {
        foreach ($payload['DeptId'] as $item) {
            if ($department = Department::query()->where('ding_id', $this->ding->id)->where('dept_id', $item)->first()) {
                //获取部门信息,然后判断存储
                $data = $this->app->department->get($item);
                if ($data['errcode']) {
                    //请求错误
                    continue;
                }
                $department->update([
                    'dept_parent_id' => $data['result']['parent_id'],
                    'name' => $data['result']['name']
                ]);
            }
        }
    }


    //保存发送的信息
    public function saveSendMessage(int $business_id, string $message_id, string $message, int $type, string $key, string $receive_id): Model|Send|Builder|_IH_Send_QB
    {
        return Send::query()->create([
            'business_id' => $business_id,
            'message_id' => $message_id,
            'receive_id' => $receive_id,
            'message' => $message,
            'type' => $type,
            'key' => $key
        ]);
    }


    /**
     * 更新部门数据
     * @throws AdminInvalidRequestException
     */
    public function updateDepartment()
    {
        try {
            $department = $this->app->department->list(1);
        } catch (Exception $exception) {
            throw new AdminInvalidRequestException(json_decode($exception->getMessage(), true)['errmsg']);
        }
        if (isset($department['result']) && count($department['result'])) {
            //如果存在部门数据，需要追加一个根部门
            if (!Department::query()->where('ding_id', $this->ding->id)->where('dept_id', 1)->exists()) {
                Department::query()->create([
                    'ding_id' => $this->ding->id,
                    'dept_parent_id' => 0,
                    'dept_id' => 1,
                    'name' => '根部门'
                ]);
            }
            $this->departmentChildren($this->ding->id, 1);
        }
    }

    /**
     * @param $ding_id
     * @param $dept_id
     * @throws AdminInvalidRequestException
     */
    protected function departmentChildren($ding_id, $dept_id)
    {
        try {
            $department = $this->app->department->list($dept_id);
            if (isset($department['result']) && count($department['result'])) {
                foreach ($department['result'] as $item) {
                    //存入数据库
                    if (!Department::query()->where('ding_id', $ding_id)->where('dept_id', $item['dept_id'])->exists()) {
                        Department::query()->create([
                            'ding_id' => $ding_id,
                            'dept_parent_id' => $item['parent_id'],
                            'dept_id' => $item['dept_id'],
                            'name' => $item['name']
                        ]);
                    }
                    //递归获取下级部门数据
                    $this->departmentChildren($ding_id, $item['dept_id']);
                }
            }
        } catch (Exception $exception) {
            throw new AdminInvalidRequestException(json_decode($exception->getMessage(), true)['errmsg']);
        }
    }


    public function updateUser()
    {
        Department::query()->where('ding_id', $this->ding->id)->chunkById(100, function ($departments) {
            foreach ($departments as $department) {
                $while = true;
                $offset = 0;
                while ($while) {
                    try {
                        $users = $this->app->user->getDetailedUsers($department->dept_id, $offset, 50, 'entry_asc');
                    } catch (Exception $exception) {
                        throw new AdminInvalidRequestException(json_decode($exception->getMessage(), true)['errmsg']);
                    }
                    if (isset($users['result']['list']) && count($users['result']['list'])) {
                        //存在用户
                        foreach ($users['result']['list'] as $user) {
                            User::updateOrCreate(
                                ['userid' => $user['userid'], 'status' => UserStatus::WORKING],
                                [
                                    'ding_id' => $this->ding->id,
                                    'dept_id' => $department->dept_id,
                                    'name' => $user['name'],
                                    'phone' => $user['mobile'],
                                    'avatar' => $user['avatar'] ?: asset('images/default.jpg'),
                                    'userid' => $user['userid'],
                                ]
                            );
                        }
                        if ($users['result']['has_more']) {
                            $offset = $offset + 1;
                        } else {
                            $while = false;
                            $offset = 0;
                        }
                    } else {
                        $while = false;
                        $offset = 0;
                    }
                }
            }
        });
    }
}
